#pragma once

#include <cstdio>
#include <string>
#include <time.h>
#include <iostream>
#include <cstdarg>
#include <unistd.h>
#include <pthread.h>
#include "LockGuard.hpp"
#include <fstream>
using std::cout;
using std::endl;

bool gIsSave = false;
const std::string logname = "log.txt";

// 1.日志是有等级的
enum Level
{
    DEBUG = 0,
    INFO,
    WARNING,
    ERROR,
    FATAL
};
std::string ToStringLevel(int level)
{
    switch (level)
    {
    case DEBUG:
        return "Debug";
    case INFO:
        return "Info";
    case WARNING:
        return "Warning";
    case ERROR:
        return "Error";
    case FATAL:
        return "Fatal";
    default:
        return "Unknow";
    }
}

std::string ToStringtime()
{
    time_t curr_time = time(nullptr);
    struct tm *format_time = localtime(&curr_time);
    if (format_time == nullptr)
        return "None";
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "%d-%d-%d %d:%d:%d",
             format_time->tm_year + 1900,
             format_time->tm_mon + 1,
             format_time->tm_mday,
             format_time->tm_hour,
             format_time->tm_min,
             format_time->tm_sec);
    return buffer;
}

void ToSave(const std::string &filename, std::string &message)
{
    std::ofstream out(filename, std::ios::app);
    if (!out.is_open())
    {
        return;
    }
    out << message;
    out.close();
}

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

// 2. 日志是由格式的
// 日志等级 时间 代码所在的文件名/行数 日志的内容
void LogMessage(std::string filename, int line, bool issave, int level, const char *format, ...)
{
    std::string levelstr = ToStringLevel(level);
    std::string timestr = ToStringtime();
    pid_t selfid = getpid();
    va_list arg;
    va_start(arg, format);
    char buffer[1024];
    vsnprintf(buffer, sizeof(buffer), format, arg);
    va_end(arg);
    std::string message;
    message = "[" + timestr + "]" + "[" + levelstr + "]" + "[pid: " + std::to_string(selfid) + "]" + buffer + "\n";

    if (!issave)
    {
        LockGuard mutex(&lock);
        // cout << levelstr << ":" << timestr << ":" << filename << ":" << line << ":" << buffer << endl;
        cout << "[" << timestr << "]"
             << "[" << levelstr << "]"
             << "[pid: " << selfid << "]"
             << buffer << endl;
    }
    else
    {
        ToSave(logname, message);
    }
}

#define LOG(level, format, ...)                                                \
    do                                                                         \
    {                                                                          \
        LogMessage(__FILE__, __LINE__, gIsSave, level, format, ##__VA_ARGS__); \
    } while (0)

#define EnableFile()    \
    do                  \
    {                   \
        gIsSave = true; \
    } while (0)
#define EnableScreen()   \
    do                   \
    {                    \
        gIsSave = false; \
    } while (0)
